<template>
  <t-dialog
    v-model:visible="show"
    :width="400"
    :header="formData.id ? $t('common.update') : $t('common.create')"
    :onConfirm="() => form.submit()"
    destroyOnClose
    :closeOnOverlayClick="false"
  >
    <template #body>
      <t-form ref="form" :data="formData" :rules="formRule" label-align="top" @submit="onSubmit">
        <t-form-item :label="plugin.t('menu.name')" name="name">
          <t-input v-model="formData.name"/>
        </t-form-item>
        <t-form-item :label="plugin.t('menu.sort')" name="sort">
          <t-input-number v-model="formData.sort" />
        </t-form-item>
      </t-form>
    </template>
    <template #footer>
      <t-button theme="primary" :loading="loading" @click="form.submit()">
        {{ formData.id ? $t('common.update') : $t('common.create') }}
      </t-button>
    </template>
  </t-dialog>
</template>
<script setup>
  import { ref } from 'vue'
  import app from '@/app'
  import menuStore from '../../store/menu'
  import index from '../../index'

  const plugin = index.plugin

  const show = ref(false)
  const loading = ref(false)
  const form = ref(null)
  const formData = ref({})
  const formRule = {
    name: [{ required: true, message: ' ', type: 'error' }],
    sort: [{ required: true, message: ' ', type: 'error' }],
    discount: [{ required: true, message: ' ', type: 'error' }]
  }
  const open = data => {
    formData.value = Object.assign({
      name: '', 
      sort: 0,
      discount: 0
    }, data)
    show.value = true
  }

  const onSubmit = ({ validateResult }) => {
    if (validateResult === true) {
      loading.value = true
      menuStore.update(formData.value).then(res => {
        show.value = false
        app.message('success', 'message.' + res.message)
      }).catch(err => {
        app.message('error', 'message.error.' + err.message)
      }).finally(() => {
        loading.value = false
      })
    }
  }

  defineExpose({ open })
</script>